package com.doubao.wechat.controller;

import com.doubao.common.result.Result;
import com.doubao.wechat.dto.request.MembershipOrderRequest;
import com.doubao.wechat.entity.PaymentOrder;
import com.doubao.wechat.mapper.PaymentOrderMapper;
import com.doubao.wechat.service.PaymentComposer;
import com.doubao.wechat.service.WxPayService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 会员支付控制器
 */
@RestController
@RequestMapping("/wechat/membership/pay")
@Slf4j
@RequiredArgsConstructor
@Tag(name = "会员支付", description = "会员订阅支付相关接口")
public class MembershipPayController {

    private final PaymentComposer paymentComposer;
    @Resource
    private PaymentOrderMapper paymentOrderMapper;

    @Resource
    private WxPayService wxPayService;
    
    /**
     * 创建会员订阅支付订单
     * 
     * @param request 支付参数
     * @return 支付订单信息
     */
    @PostMapping
    @Operation(summary = "创建会员订阅订单", description = "创建会员订阅支付订单")
    public Result<Map<String, Object>> createSubscriptionOrder(@RequestBody MembershipOrderRequest request) {
        log.info("创建会员订阅订单: {}", request);
        
        // 参数校验
        if (request.getUserId() == null || request.getUserId() <= 0) {
            return Result.failed("用户ID不能为空或无效");
        }
        
        if (request.getLevelId() == null || request.getLevelId() <= 0) {
            return Result.failed("会员等级ID不能为空或无效");
        }
        
        Integer amount = request.getAmount();
        if (amount == null || amount <= 0) {
            amount = 990; // 默认0.9元，与数据库中的月卡价格一致
        }
        
        log.info("会员订阅支付金额: {} 分 ({} 元)", amount, amount / 100.0);
        
        String payType = request.getPayType();
        if (payType == null || payType.isEmpty()) {
            payType = "jsapi"; // 默认jsapi
        }
        
        String clientIp = request.getClientIp();
        if (clientIp == null || clientIp.isEmpty()) {
            clientIp = "127.0.0.1"; // 默认IP
        }
        
        try {
            // 调用支付服务创建订单
            return paymentComposer.createMembershipOrder(request.getUserId(), request.getLevelId(), amount, payType, clientIp);
        } catch (Exception e) {
            log.error("创建会员订阅订单失败", e);
            return Result.failed("创建支付订单失败: 系统繁忙，请稍后再试");
        }
    }

    /**
     * 查询会员订单
     *
     * @param outTradeNo 商户订单号
     * @param userId 用户ID
     * @return 订单信息
     */
    @GetMapping("/order/{outTradeNo}")
    @Operation(summary = "查询会员订单", description = "根据订单号查询会员支付订单")
    public Result<Map<String, Object>> queryMembershipOrder(
            @PathVariable("outTradeNo") String outTradeNo,
            @RequestHeader(value = "X-User-ID", required = false) Long userId) {

        log.info("查询会员订单: outTradeNo={}, userId={}", outTradeNo, userId);

        try {
            // 查询订单
            PaymentOrder order = paymentOrderMapper.selectByOutTradeNo(outTradeNo);
            if (order == null) {
                log.error("订单不存在: {}", outTradeNo);
                return Result.failed("订单不存在");
            }

            // 验证用户
            if (userId != null && !userId.equals(order.getUserId())) {
                log.error("无权访问该订单: outTradeNo={}, userId={}, orderUserId={}",
                        outTradeNo, userId, order.getUserId());
                return Result.failed("无权访问该订单");
            }

            // 构建返回数据
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("localOrder", order);
            resultMap.put("status", order.getStatus());

            // 如果订单已支付，尝试从微信服务查询
            if ("SUCCESS".equals(order.getStatus())) {
                try {
                    Result<Map<String, Object>> wxOrderResult = wxPayService.queryOrder(outTradeNo);
                    if (wxOrderResult.isSuccess()) {
                        resultMap.put("wxOrder", wxOrderResult.getData());
                    }
                } catch (Exception e) {
                    log.warn("查询微信订单详情失败: {}", e.getMessage());
                    // 不影响主流程，继续返回本地订单信息
                }
            }

            return Result.success(resultMap);
        } catch (Exception e) {
            log.error("查询会员订单异常", e);
            return Result.failed("查询订单异常: " + e.getMessage());
        }
    }

    /**
     * 会员支付测试接口
     */
    @GetMapping("/test")
    public Result<Map<String, Object>> testPay() {
        log.info("测试会员支付接口");
        Map<String, Object> result = new HashMap<>();
        result.put("msg", "会员支付接口测试成功");
        result.put("code", 200);
        return Result.success(result);
    }
}